package com.jx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jx.dao.SearchMapper;
import com.jx.dto.AttrDto;
import com.jx.dto.GoodDto;
import com.jx.pojo.Attr;
import com.jx.pojo.Good;
import com.jx.pojo.ParamObj;
import com.jx.pojo.Trademark;
import com.jx.service.SearchService;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private SearchMapper searchMapper;

    /**
     * 获取属性数据
     *
     * @return
     */
    @Override
    public List<AttrDto> getAttrList() {
        // 获取所有的attr数据
        List<Attr> attrList = searchMapper.getAttrList();
        // 将floor数据转换为dto类型
        List<AttrDto> attrDtoList = attrList.stream().map(attr -> {
            AttrDto attrDto = new AttrDto();
            // 将attr中的属性复制到attrDto中
            BeanUtils.copyProperties(attr, attrDto, "attrValueList");
            // 将attr中的attrValueList属性转换为数组
            attrDto.setAttrValueList(attr.getAttrValueList().split(","));
            // 返回attrDto
            return attrDto;
        }).collect(Collectors.toList());
        return attrDtoList;
    }

    /**
     * 获取品牌数据
     *
     * @return
     */
    @Override
    public List<Trademark> getTrademarkList() {
        List<Trademark> trademarkList = searchMapper.getTrademarkList();
        return trademarkList;
    }

    /**
     * 获取商品数据
     * (pageNo-1)*pageSize + 1
     * @return
     */
    @Override
    public GoodDto getGoodsListByConditionAndPage(ParamObj paramObj) {
        // 处理参数： 华为 → %华为%   1:小米 → 小米
        if(paramObj.getKeyword() != "" && paramObj.getKeyword() != null) {
            paramObj.setKeyword("%" + paramObj.getKeyword() + "%");
        }
        if(paramObj.getTrademark() != "" && paramObj.getTrademark() != null) {
            paramObj.setTrademark(paramObj.getTrademark().split(":")[1]);
        }
        // 计算当前页第一条数据
        paramObj.setBegin((paramObj.getPageNo() - 1) * paramObj.getPageSize() );
        // 获取商品列表数据
        List<Good> goodsList = searchMapper.getGoodsListByConditionAndPage(paramObj);
        // 获取总记录数
        int count = searchMapper.getCountByConditionAndPage(paramObj);
        System.out.println(count);
        // 数据封装成goodDto返回
        GoodDto goodDto = new GoodDto();
        goodDto.setGoodsList(goodsList);
        goodDto.setTotal(count);
        goodDto.setPageNo(paramObj.getPageNo());
        goodDto.setPageSize(paramObj.getPageSize());
        goodDto.setTotalPages((count/paramObj.getPageSize())+1);
        System.out.println(goodDto);
        return goodDto;
    }
}
